<template>
  <div class="profile-settings">
    <div class="page-header">
      <div class="header-left">
        <h2>个人设置</h2>
        <p>个性化配置您的账户偏好和系统设置</p>
      </div>
    </div>

    <div class="settings-content">
      <el-row :gutter="24">
        <!-- 左侧：设置分类 -->
        <el-col :span="6">
          <el-card class="settings-nav">
            <div class="nav-list">
              <div
                v-for="item in navItems"
                :key="item.key"
                class="nav-item"
                :class="{ active: activeTab === item.key }"
                @click="activeTab = item.key"
              >
                <el-icon class="nav-icon">
                  <component :is="item.icon" />
                </el-icon>
                <span class="nav-text">{{ item.label }}</span>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 右侧：设置内容 -->
        <el-col :span="18">
          <!-- 基本设置 -->
          <el-card v-if="activeTab === 'basic'" class="settings-card">
            <template #header>
              <span>基本设置</span>
            </template>
            
            <el-form
              ref="basicForm"
              :model="basicSettings"
              label-width="120px"
            >
              <el-form-item label="语言设置">
                <el-select v-model="basicSettings.language" style="width: 200px">
                  <el-option label="简体中文" value="zh-CN" />
                  <el-option label="English" value="en-US" />
                </el-select>
              </el-form-item>
              
              <el-form-item label="主题设置">
                <el-radio-group v-model="basicSettings.theme">
                  <el-radio label="light">浅色主题</el-radio>
                  <el-radio label="dark">深色主题</el-radio>
                  <el-radio label="auto">跟随系统</el-radio>
                </el-radio-group>
              </el-form-item>
              
              <el-form-item label="字体大小">
                <el-slider
                  v-model="basicSettings.fontSize"
                  :min="12"
                  :max="20"
                  :step="1"
                  show-input
                  style="width: 300px"
                />
              </el-form-item>
              
              <el-form-item label="页面布局">
                <el-radio-group v-model="basicSettings.layout">
                  <el-radio label="default">默认布局</el-radio>
                  <el-radio label="compact">紧凑布局</el-radio>
                  <el-radio label="wide">宽屏布局</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-form>
          </el-card>

          <!-- 通知设置 -->
          <el-card v-if="activeTab === 'notification'" class="settings-card">
            <template #header>
              <span>通知设置</span>
            </template>
            
            <el-form
              ref="notificationForm"
              :model="notificationSettings"
              label-width="120px"
            >
              <el-form-item label="系统通知">
                <el-switch v-model="notificationSettings.systemNotification" />
              </el-form-item>
              
              <el-form-item label="邮件通知">
                <el-switch v-model="notificationSettings.emailNotification" />
              </el-form-item>
              
              <el-form-item label="短信通知">
                <el-switch v-model="notificationSettings.smsNotification" />
              </el-form-item>
              
              <el-form-item label="浏览器通知">
                <el-switch v-model="notificationSettings.browserNotification" />
              </el-form-item>
              
              <el-divider content-position="left">通知类型</el-divider>
              
              <el-form-item label="商品更新">
                <el-switch v-model="notificationSettings.productUpdate" />
              </el-form-item>
              
              <el-form-item label="质量检测">
                <el-switch v-model="notificationSettings.qualityInspection" />
              </el-form-item>
              
              <el-form-item label="库存预警">
                <el-switch v-model="notificationSettings.inventoryWarning" />
              </el-form-item>
              
              <el-form-item label="系统维护">
                <el-switch v-model="notificationSettings.systemMaintenance" />
              </el-form-item>
            </el-form>
          </el-card>

          <!-- 隐私设置 -->
          <el-card v-if="activeTab === 'privacy'" class="settings-card">
            <template #header>
              <span>隐私设置</span>
            </template>
            
            <el-form
              ref="privacyForm"
              :model="privacySettings"
              label-width="120px"
            >
              <el-form-item label="数据收集">
                <el-switch v-model="privacySettings.dataCollection" />
                <div class="setting-desc">允许系统收集使用数据以改善服务</div>
              </el-form-item>
              
              <el-form-item label="个性化推荐">
                <el-switch v-model="privacySettings.personalizedRecommendation" />
                <div class="setting-desc">基于您的使用习惯提供个性化推荐</div>
              </el-form-item>
              
              <el-form-item label="位置信息">
                <el-switch v-model="privacySettings.locationAccess" />
                <div class="setting-desc">允许系统访问您的位置信息</div>
              </el-form-item>
              
              <el-form-item label="在线状态">
                <el-select v-model="privacySettings.onlineStatus" style="width: 200px">
                  <el-option label="所有人可见" value="public" />
                  <el-option label="仅好友可见" value="friends" />
                  <el-option label="仅自己可见" value="private" />
                </el-select>
              </el-form-item>
              
              <el-form-item label="搜索可见性">
                <el-select v-model="privacySettings.searchVisibility" style="width: 200px">
                  <el-option label="允许被搜索" value="public" />
                  <el-option label="仅好友可搜索" value="friends" />
                  <el-option label="不允许搜索" value="private" />
                </el-select>
              </el-form-item>
            </el-form>
          </el-card>

          <!-- 安全设置 -->
          <el-card v-if="activeTab === 'security'" class="settings-card">
            <template #header>
              <span>安全设置</span>
            </template>
            
            <el-form
              ref="securityForm"
              :model="securitySettings"
              label-width="120px"
            >
              <el-form-item label="两步验证">
                <el-switch v-model="securitySettings.twoFactorAuth" />
                <div class="setting-desc">启用两步验证以提高账户安全性</div>
              </el-form-item>
              
              <el-form-item label="登录设备管理">
                <el-button @click="showDeviceManagement = true">
                  管理登录设备
                </el-button>
                <div class="setting-desc">查看和管理已登录的设备</div>
              </el-form-item>
              
              <el-form-item label="登录历史">
                <el-button @click="showLoginHistory = true">
                  查看登录历史
                </el-button>
                <div class="setting-desc">查看最近的登录记录</div>
              </el-form-item>
              
              <el-form-item label="自动锁定">
                <el-switch v-model="securitySettings.autoLock" />
                <div class="setting-desc">空闲时自动锁定账户</div>
              </el-form-item>
              
              <el-form-item label="锁定时间" v-if="securitySettings.autoLock">
                <el-select v-model="securitySettings.lockTime" style="width: 200px">
                  <el-option label="5分钟" value="5" />
                  <el-option label="10分钟" value="10" />
                  <el-option label="30分钟" value="30" />
                  <el-option label="1小时" value="60" />
                </el-select>
              </el-form-item>
            </el-form>
          </el-card>

          <!-- 数据设置 -->
          <el-card v-if="activeTab === 'data'" class="settings-card">
            <template #header>
              <span>数据设置</span>
            </template>
            
            <el-form
              ref="dataForm"
              :model="dataSettings"
              label-width="120px"
            >
              <el-form-item label="数据备份">
                <el-button type="primary" @click="backupData">
                  立即备份
                </el-button>
                <div class="setting-desc">备份您的个人数据到云端</div>
              </el-form-item>
              
              <el-form-item label="自动备份">
                <el-switch v-model="dataSettings.autoBackup" />
                <div class="setting-desc">定期自动备份数据</div>
              </el-form-item>
              
              <el-form-item label="备份频率" v-if="dataSettings.autoBackup">
                <el-select v-model="dataSettings.backupFrequency" style="width: 200px">
                  <el-option label="每天" value="daily" />
                  <el-option label="每周" value="weekly" />
                  <el-option label="每月" value="monthly" />
                </el-select>
              </el-form-item>
              
              <el-form-item label="数据导出">
                <el-button @click="exportData">
                  导出数据
                </el-button>
                <div class="setting-desc">导出您的个人数据</div>
              </el-form-item>
              
              <el-form-item label="清除数据">
                <el-button type="danger" @click="showClearData = true">
                  清除数据
                </el-button>
                <div class="setting-desc">永久删除您的所有数据（不可恢复）</div>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 保存按钮 -->
    <div class="settings-footer">
      <el-button @click="resetSettings">重置</el-button>
      <el-button type="primary" @click="saveSettings" :loading="saveLoading">
        保存设置
      </el-button>
    </div>

    <!-- 设备管理对话框 -->
    <el-dialog
      v-model="showDeviceManagement"
      title="登录设备管理"
      width="600px"
    >
      <el-table :data="loginDevices" style="width: 100%">
        <el-table-column prop="device" label="设备" />
        <el-table-column prop="location" label="位置" />
        <el-table-column prop="lastLogin" label="最后登录" />
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="row.status === 'current' ? 'success' : 'info'">
              {{ row.status === 'current' ? '当前设备' : '其他设备' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button
              v-if="row.status !== 'current'"
              type="danger"
              size="small"
              @click="logoutDevice(row)"
            >
              退出登录
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 登录历史对话框 -->
    <el-dialog
      v-model="showLoginHistory"
      title="登录历史"
      width="600px"
    >
      <el-table :data="loginHistory" style="width: 100%">
        <el-table-column prop="time" label="登录时间" />
        <el-table-column prop="device" label="设备" />
        <el-table-column prop="location" label="位置" />
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="row.status === 'success' ? 'success' : 'danger'">
              {{ row.status === 'success' ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 清除数据确认对话框 -->
    <el-dialog
      v-model="showClearData"
      title="清除数据确认"
      width="400px"
    >
      <div class="clear-data-warning">
        <el-icon class="warning-icon"><Warning /></el-icon>
        <p>此操作将永久删除您的所有数据，包括：</p>
        <ul>
          <li>个人信息</li>
          <li>设置偏好</li>
          <li>操作历史</li>
          <li>其他相关数据</li>
        </ul>
        <p><strong>此操作不可恢复！</strong></p>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showClearData = false">取消</el-button>
          <el-button type="danger" @click="clearData" :loading="clearLoading">
            确认清除
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Setting, 
  Bell, 
  Lock, 
  DataAnalysis, 
  User,
  Warning 
} from '@element-plus/icons-vue'

export default defineComponent({
  name: 'ProfileSettings',
  components: {
    Setting,
    Bell,
    Lock,
    DataAnalysis,
    User,
    Warning
  },
  setup() {
    const activeTab = ref('basic')
    const saveLoading = ref(false)
    const clearLoading = ref(false)
    const showDeviceManagement = ref(false)
    const showLoginHistory = ref(false)
    const showClearData = ref(false)
    
    // 导航项
    const navItems = [
      { key: 'basic', label: '基本设置', icon: 'Setting' },
      { key: 'notification', label: '通知设置', icon: 'Bell' },
      { key: 'privacy', label: '隐私设置', icon: 'User' },
      { key: 'security', label: '安全设置', icon: 'Lock' },
      { key: 'data', label: '数据设置', icon: 'DataAnalysis' }
    ]
    
    // 基本设置
    const basicSettings = reactive({
      language: 'zh-CN',
      theme: 'light',
      fontSize: 14,
      layout: 'default'
    })
    
    // 通知设置
    const notificationSettings = reactive({
      systemNotification: true,
      emailNotification: true,
      smsNotification: false,
      browserNotification: true,
      productUpdate: true,
      qualityInspection: true,
      inventoryWarning: true,
      systemMaintenance: false
    })
    
    // 隐私设置
    const privacySettings = reactive({
      dataCollection: true,
      personalizedRecommendation: true,
      locationAccess: false,
      onlineStatus: 'public',
      searchVisibility: 'public'
    })
    
    // 安全设置
    const securitySettings = reactive({
      twoFactorAuth: false,
      autoLock: true,
      lockTime: '30'
    })
    
    // 数据设置
    const dataSettings = reactive({
      autoBackup: true,
      backupFrequency: 'weekly'
    })
    
    // 登录设备
    const loginDevices = ref([
      {
        device: 'Chrome - Windows 10',
        location: '北京',
        lastLogin: '2024-01-15 10:30',
        status: 'current'
      },
      {
        device: 'Safari - iPhone',
        location: '上海',
        lastLogin: '2024-01-14 15:20',
        status: 'other'
      },
      {
        device: 'Firefox - MacOS',
        location: '深圳',
        lastLogin: '2024-01-13 09:15',
        status: 'other'
      }
    ])
    
    // 登录历史
    const loginHistory = ref([
      {
        time: '2024-01-15 10:30',
        device: 'Chrome - Windows 10',
        location: '北京',
        status: 'success'
      },
      {
        time: '2024-01-14 15:20',
        device: 'Safari - iPhone',
        location: '上海',
        status: 'success'
      },
      {
        time: '2024-01-13 09:15',
        device: 'Firefox - MacOS',
        location: '深圳',
        status: 'success'
      },
      {
        time: '2024-01-12 16:45',
        device: 'Unknown',
        location: '未知',
        status: 'failed'
      }
    ])
    
    // 保存设置
    const saveSettings = async () => {
      saveLoading.value = true
      try {
        // 模拟API请求
        await new Promise(resolve => setTimeout(resolve, 1000))
        ElMessage.success('设置保存成功')
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败')
      } finally {
        saveLoading.value = false
      }
    }
    
    // 重置设置
    const resetSettings = () => {
      ElMessageBox.confirm(
        '确定要重置所有设置吗？此操作不可撤销。',
        '确认重置',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        // 重置所有设置
        Object.assign(basicSettings, {
          language: 'zh-CN',
          theme: 'light',
          fontSize: 14,
          layout: 'default'
        })
        
        Object.assign(notificationSettings, {
          systemNotification: true,
          emailNotification: true,
          smsNotification: false,
          browserNotification: true,
          productUpdate: true,
          qualityInspection: true,
          inventoryWarning: true,
          systemMaintenance: false
        })
        
        Object.assign(privacySettings, {
          dataCollection: true,
          personalizedRecommendation: true,
          locationAccess: false,
          onlineStatus: 'public',
          searchVisibility: 'public'
        })
        
        Object.assign(securitySettings, {
          twoFactorAuth: false,
          autoLock: true,
          lockTime: '30'
        })
        
        Object.assign(dataSettings, {
          autoBackup: true,
          backupFrequency: 'weekly'
        })
        
        ElMessage.success('设置已重置')
      }).catch(() => {
        // 用户取消
      })
    }
    
    // 备份数据
    const backupData = async () => {
      try {
        ElMessage.success('数据备份成功')
      } catch (error) {
        console.error('备份失败:', error)
        ElMessage.error('备份失败')
      }
    }
    
    // 导出数据
    const exportData = async () => {
      try {
        ElMessage.success('数据导出成功')
      } catch (error) {
        console.error('导出失败:', error)
        ElMessage.error('导出失败')
      }
    }
    
    // 退出设备登录
    const logoutDevice = (device) => {
      ElMessageBox.confirm(
        `确定要退出设备 "${device.device}" 的登录吗？`,
        '确认退出',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        // 从列表中移除设备
        const index = loginDevices.value.findIndex(d => d.device === device.device)
        if (index > -1) {
          loginDevices.value.splice(index, 1)
        }
        ElMessage.success('设备已退出登录')
      }).catch(() => {
        // 用户取消
      })
    }
    
    // 清除数据
    const clearData = async () => {
      clearLoading.value = true
      try {
        // 模拟API请求
        await new Promise(resolve => setTimeout(resolve, 2000))
        ElMessage.success('数据清除成功')
        showClearData.value = false
      } catch (error) {
        console.error('清除失败:', error)
        ElMessage.error('清除失败')
      } finally {
        clearLoading.value = false
      }
    }
    
    onMounted(() => {
      // 加载用户设置
    })
    
    return {
      activeTab,
      saveLoading,
      clearLoading,
      showDeviceManagement,
      showLoginHistory,
      showClearData,
      navItems,
      basicSettings,
      notificationSettings,
      privacySettings,
      securitySettings,
      dataSettings,
      loginDevices,
      loginHistory,
      saveSettings,
      resetSettings,
      backupData,
      exportData,
      logoutDevice,
      clearData
    }
  }
})
</script>

<style scoped>
.profile-settings {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left h2 {
  margin: 0 0 5px 0;
  color: #2563eb;
}

.header-left p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.settings-content {
  margin-bottom: 20px;
}

.settings-nav {
  .nav-list {
    .nav-item {
      display: flex;
      align-items: center;
      padding: 12px 16px;
      cursor: pointer;
      border-radius: 6px;
      margin-bottom: 8px;
      transition: all 0.3s;
      
      &:hover {
        background-color: #f5f7fa;
      }
      
      &.active {
        background-color: #e6f7ff;
        color: #1890ff;
      }
      
      .nav-icon {
        margin-right: 12px;
        font-size: 16px;
      }
      
      .nav-text {
        font-size: 14px;
      }
    }
  }
}

.settings-card {
  .setting-desc {
    font-size: 12px;
    color: #666;
    margin-top: 4px;
  }
}

.settings-footer {
  display: flex;
  justify-content: center;
  gap: 16px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.clear-data-warning {
  text-align: center;
  
  .warning-icon {
    font-size: 48px;
    color: #f56c6c;
    margin-bottom: 16px;
  }
  
  p {
    margin: 8px 0;
  }
  
  ul {
    text-align: left;
    margin: 16px 0;
    padding-left: 20px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

@media (max-width: 768px) {
  .settings-content {
    .el-col {
      margin-bottom: 20px;
    }
  }
  
  .settings-nav {
    margin-bottom: 20px;
  }
}
</style> 